package com.example.hosptial.service.impl;

import com.example.hosptial.model.enity.Patient;
import com.example.hosptial.model.view.WardBedPatientView;
import com.example.hosptial.model.view.WardStatusView;
import com.example.hosptial.repository.PatientRepository;
import com.example.hosptial.repository.WardBedPatientViewRepository;
import com.example.hosptial.repository.WardStatusRepository;
import com.example.hosptial.service.BedTransferService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BedTransferServiceImpl implements BedTransferService {

    private static final Logger logger = LoggerFactory.getLogger(BedTransferServiceImpl.class);

    @Autowired
    private WardStatusRepository wardStatusViewRepository;

    @Autowired
    private WardBedPatientViewRepository wardBedPatientViewRepository;

    @Autowired
    private PatientRepository patientRepository;

    @Override
    public List<Integer> getFloorsByDeptId(Integer deptId) {
        return wardStatusViewRepository.findDistinctFloorNumByDeptId(deptId);
    }

    @Override
    public List<WardStatusView> getAvailableWardsByDeptIdAndFloor(Integer deptId, Integer floorNum) {
        return wardStatusViewRepository.findByDeptIdAndFloorNum(deptId, floorNum)
                .stream()
                .filter(ward -> ward.getAvailableBeds() > 0)
                .collect(Collectors.toList());
    }

    @Override
    public List<WardBedPatientView> getAvailableBedsByWardId(Integer wardId) {
        return wardBedPatientViewRepository.findByWardIdAndBedStatus(wardId, 2); // 2表示空闲
    }

    @Override
    @Transactional
    public boolean transferBed(Integer patientId, Integer newBedId) {
        try {
            // 检查病人是否存在
            Patient patient = patientRepository.findById(patientId)
                    .orElseThrow(() -> new IllegalArgumentException("患者不存在"));

            // 检查新床位是否可用
            WardBedPatientView newBed = wardBedPatientViewRepository.findById(newBedId)
                    .orElseThrow(() -> new IllegalArgumentException("目标床位不存在"));

            if (newBed.getBedStatus() != 2) { // 2表示空闲
                throw new IllegalStateException("目标床位已被占用，请刷新后重试");
            }

            // 调用存储过程执行换床操作
            patientRepository.transferBed(patientId, newBedId);
            
            logger.info("病人 {} 成功转移到床位 {}", patientId, newBedId);
            return true;
        } catch (IllegalArgumentException | IllegalStateException e) {
            logger.warn("换床失败: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("换床操作异常: {}", e.getMessage(), e);
            throw new RuntimeException("换床操作失败，请稍后重试");
        }
    }
}